package net.streaming.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class MainModel {
	private Client client = new Client();
	private ReadThread readThread;
	private boolean connected;
	/**
	 * 
	 * @param url 127.0.0.1:80
	 */
	public void connect(String url){
		this.disConnect();
		String[] addrs = url.split(" ");
		client.setIp(addrs[0]);
		client.setPort(Integer.parseInt(addrs[1]));
		try {
			this.client.open();
			this.connected = true;
			System.out.println("connect to : " + url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void disConnect(){
		try {
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(this.readThread!=null){
			this.readThread.stopLoop();
		}
		this.readThread=null;
		this.connected = true;
	}
	
	public void send(String str, String format){
		byte[] buf = null;
		if("Hex".equals(format)){
			buf = Hex.decodeHex(str);
		}else if("Binary".equals(format)){
			buf = Binary.decodeBinary(str);
		}else{
			try {
				str = str.replaceAll("\\r", "");
				str = str.replaceAll("\\n", "\\\r\\\n");
				buf = str.getBytes("utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		try {
			client.send(buf);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void receive(Handle handle){
		if(readThread==null){
			readThread = new ReadThread(client.getInputStream(), handle);
			readThread.start();	
		}
	}

	public boolean isConnected() {
		return connected;
	}

}
